<template>
  <div class="module-item">
    <component v-loading="filterLoading" ref="componentEchartRef" :is="componentName" v-bind="$attrs" :module-item-data="moduleItemData" v-on="$listeners"/>
    <el-tooltip v-if="showFilterPopover" :delay="800" placeholder="top" content="刷新">
      <el-image :src="freshIcon" :class="{'right': !exportAuth}" class="fresh-img" @click="searchData"/>
    </el-tooltip>
    <div v-if="exportAuth" class="export-container">
      <export-button
        ref="totalExportRef"
        :export-api="'/admin/charts/export?id='+moduleItemData.id"
        :export-name="moduleItemData.name || '导出数据'"
        :format="'xlsx'"
        :is-before-export="true"
        :http-method="'post'"
        is-diy
        @onComplate="exportComplate"
        @onErrorExport="onErrorExport"
        @beforeExport="chartsPreview">
        <el-tooltip v-if="!exportLoading" :delay="800" placeholder="top" content="导出">
          <el-image :src="exportIcon" class="export-container-btn"/>
        </el-tooltip>
        <i v-else class="el-icon-loading"/>
      </export-button>
    </div>
    <el-tooltip v-if="showFilterPopover" :delay="800" placeholder="top" content="筛选">
      <div class="time-select">
        <FilterPopover
          ref="filterPopover"
          v-model="popoverFilterData"
          :insert-filter-list="filterList"
          :hide-btn="filterList.length === 0 && !(moduleItemData.kind === 3 && isTimeField(moduleItemData.xAxis))"
          :init="filterPopoverInit"
          title="数据筛选"
          mode="single"
          empty-text="暂无筛选项，可通过编辑图表数据筛选开启图表筛选项及配置默认筛选条件"
          append-to-body
          @show="popoverShowFun"
          @handelAllChange="searchData">
          <!-- kind: 3 图表类 -->
          <popoverFilter v-if="moduleItemData.kind === 3 && isTimeField(moduleItemData.xAxis)" v-model="popoverFilterShowType" />
        </FilterPopover>
      </div>
    </el-tooltip>
    <ChartsPreviewDialog
      ref="ChartsPreviewDialogRef"
      :title="moduleItemData.name"
      :table-data="moduleItemData.tableData"
      @handleExport="beforeExport('totalExportRef')"
    />
  </div>
</template>

<script>
import items from './items';
import popoverFilter from './popoverFilter';
import FilterPopover from '@/components/DashboardPage/filterPopover';
import ExportButton from '@/components/ExportButton';
import ChartsPreviewDialog from './chartsPreviewDialog';
import { hasRouteAuth } from '@/utils/permission';
import exportIcon from '@/assets/chartsTheme/export.png';
import freshIcon from '@/assets/chartsTheme/fresh.png';
export default {
  name: 'ModuleItem',
  components: {
    ...items,
    popoverFilter,
    FilterPopover,
    ExportButton,
    ChartsPreviewDialog
  },
  inheritAttrs: false, // inheritAttrs默认值为true，true的意思是将父组件中除了props外的属性添加到子组件的根节点上(说明，即使设置为true，子组件仍然可以通过$attr获取到props意外的属性),将inheritAttrs:false后,属性就不会显示在根节点上了
  props: {
    isFullscreen: {
      type: Boolean,
      default: false
    },
    chartIndex: {
      type: Number,
      default: 1
    },
    isCanEdit: {
      type: Boolean,
      default: false
    },
    moduleItemData: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      exportIcon, freshIcon,
      names: {
        1: 'TagItem',
        2: 'TableItem',
        3: 'ChartItem',
        4: 'NumberItem',
        5: 'TitleItem',
        6: 'HomeItem'
      },
      popoverFilterData: {},
      filterLoading: false,
      filterPopoverInit: false,
      exportLoading: false,
      popoverFilterShowType: {
        showType: ''
      }
    };
  },
  computed: {
    componentName() {
      return this.names[this.moduleItemData.kind];
    },
    filterList() {
      const chartFilter = this.moduleItemData.chartFilter;
      const arr = this.handelFilter(this.moduleItemData, chartFilter) || [];
      return arr;
    },
    showFilterPopover() {
      return !this.isEmpty(this.moduleItemData) && !this.isCanEdit &&
        !this.isFullscreen && !['TitleItem', 'HomeItem'].includes(this.componentName);
    },
    exportAuth() {
      // 导出权限
      return hasRouteAuth('chart:departEdit:export') &&
      !this.isEmpty(this.moduleItemData) && !this.isCanEdit &&
      (this.componentName === 'TableItem' || this.componentName === 'ChartItem');
    }
  },
  methods: {
    hasRouteAuth,
    popoverShowFun() {
      const dataShowType = this.moduleItemData.dataShowType || '';
      if (!this.popoverFilterShowType.showType && this.popoverFilterShowType.showType !== 0) {
        if (dataShowType === '按天展示') {
          this.$set(this.popoverFilterShowType, 'showType', 0);
        } else if (dataShowType === '按月展示') {
          this.$set(this.popoverFilterShowType, 'showType', 1);
        }
      }
    },
    setGlobalParams(globalParams) {
      // Object.assign(this.popoverFilterData, globalParams);
      this.popoverFilterData = globalParams;
      this.searchData();
    },
    searchData() {
      const params = this.getParams();
      this.filterLoading = true;
      this.filterPopoverInit = true;
      this.$emit('handelFilterChange', { params, index: this.chartIndex }, () => {
        this.filterLoading = false;
      });
    },
    getParams() {
      const popoverFilterData = JSON.parse(JSON.stringify(this.popoverFilterData));
      for (const key in popoverFilterData) {
        if ((Array.isArray(popoverFilterData[key]) && popoverFilterData[key].length === 0) || !popoverFilterData[key]) {
          delete popoverFilterData[key];
        }
        if (Array.isArray(popoverFilterData[key]) && popoverFilterData[key].length === 2) {
          for (let i = 0; i < popoverFilterData[key].length; i++) {
            if (!popoverFilterData[key][i] && popoverFilterData[key][i] !== 0) popoverFilterData[key][i] = null;
          }
          if (!popoverFilterData[key][0] && popoverFilterData[key][0] !== 0 && !popoverFilterData[key][1] && popoverFilterData[key][1] !== 0) {
            delete popoverFilterData[key];
          }
        }
      }

      const params = {
        id: this.moduleItemData.id,
        filter: popoverFilterData
      };
      if (popoverFilterData.isGlobal) { // isGlobal 参数提级
        params.isGlobal = true;
        delete popoverFilterData.isGlobal;
      } else {
        delete params.isGlobal;
      }
      if (this.popoverFilterShowType.showType || this.popoverFilterShowType.showType === 0) {
        params.showType = this.popoverFilterShowType.showType;
      }
      return params;
    },
    isTimeField(field) {
      if (!field) return false;
      return field.indexOf('日期') >= 0 || field.indexOf('时间') >= 0 || field === '预计到款';
    },
    resetEchart() {
      this.$refs['componentEchartRef'].resetEchart();
    },
    /**
     * 处理filterList
     */
    handelFilter(moduleItemData, filter) {
      // kind（1:概览标签 2:表格 3: 图表 5:标题）
      const kind = moduleItemData.kind;
      if (kind === 2 || kind === 3) {
        if (!filter || filter.length === 0) return [];
        const chartFilter = JSON.parse(JSON.stringify(filter));
        return this.mergeFilter(chartFilter, 'system');
      } else if (kind === 1) {
        const tags = JSON.parse(JSON.stringify(moduleItemData.tags));
        return this.mergeFilter(tags, 'dataItemFiltering');
      }
    },
    mergeFilter(arr, key) {
      const systemList = [];
      arr.forEach(i => {
        if (i[key] && i[key].length) {
          i[key].forEach(j => {
            if (j.isOpenFilter && j.field) {
              const temp = systemList.find(system => system.field === j.field);
              if (!temp) {
                systemList.push(j);
              } else {
                if (j.defaultValue) temp.defaultValue = temp.defaultValue ? `${temp.defaultValue},${j.defaultValue}` : j.defaultValue;
              }
            }
          });
        }
      });
      return systemList;
    },
    isTime(item) {
      // 字段的字段类型 optionsType  0:文本型 1:  时间日期  2: 数值型   3: 部门
      const optionsType = item.optionsType;
      // 如果 optionsType 存在则使用新逻辑，不存在则使用旧逻辑
      if (optionsType || optionsType === 0) {
        return optionsType === 1;
      }
      return item.field.indexOf('日期') >= 0 || item.field.indexOf('时间') >= 0 || item.field === '预计到款';
    },
    isEmpty(obj) {
      return Object.keys(obj).length === 0;
    },
    exportComplate() {
      this.exportLoading = false;
    },
    onErrorExport() {
      this.exportLoading = false;
    },
    chartsPreview() {
      this.$refs['ChartsPreviewDialogRef'].dialogVisible = true;
    },
    beforeExport(exportRef) {
      const params = this.getParams();
      this.exportLoading = true;
      params.isInit = false;
      this.$refs[exportRef].btnExport(params);
    },
    /**
     * 获取数据
     */
    getInfo(item, key) {
      const dataInfo = this.dataInfoObj[item.i];
      return dataInfo && dataInfo[key];
    }
  }
};
</script>

<style lang="scss" scoped>
.module-item {
  height: 100%;
  overflow: hidden;
  .fresh-img {
    position: absolute;
    right: 68px;
    top: 12px;
    display: flex;
    align-items: center;
    width: 20px;
    height: 20px;
    cursor: pointer;
    display: none;
    &.right {
      right: 41px;
    }
  }
  .time-select {
    position: absolute;
    right: 13px;
    top: 12px;
    display: flex;
    align-items: center;
    margin: 0;
    ::v-deep {
      .el-select {
        height: 32px;
        display: flex;
        align-items: center;
        .el-input {
          width: 100px !important;
          height: 32px;
          display: flex;
          align-items: center;
        }
        .el-input__suffix {
          display: flex;
          align-items: center;
        }
        .el-input__inner {
          width: 100px !important;
          height: 32px;
        }
      }
      .el-date-editor {
        width: 224px;
        height: 32px;
        padding-right: 0;
        .el-range__icon {
          line-height: 24px;
        }
        .el-range__close-icon  {
          line-height: 24px;
          text-align: left;
        }
      }
      .el-range-separator {
        width: 10%;
        font-size: 13px;
        align-items: center;
        display: flex;
      }
    }
  }
}
.filter-time-main {
  &::v-deep {
    .el-select {
      .el-input__inner {
        border-top-right-radius: 0;
        border-bottom-right-radius: 0;
        border-right: none;
      }
    }
    .el-range-editor {
      border-top-left-radius: 0;
      border-bottom-left-radius: 0;
    }
  }
}
.export-container {
  position: absolute;
  right: 41px;
  top: 6px;
  display: none;
  .export-container-btn  {
    width: 20px;
    height: 20px;
    cursor: pointer;
    >img {
      width: 100%;
      height: 100%;
    }
  }
}
</style>

<style lang="scss">
.time-select-style {
  .filter-time-main {
    .el-select {
      height: 32px;
      display: flex;
      align-items: center;
      .el-select-dropdown__item {
        font-size: 13px;
      }
      .el-input {
        width: 100px !important;
        height: 32px;
        display: flex;
        align-items: center;
      }
      .el-input__suffix {
        display: flex;
        align-items: center;
      }
      .el-input__inner {
        width: 100px !important;
        height: 32px;
      }
    }
    .el-date-editor {
      width: 224px;
      height: 32px;
      padding-right: 0;
      .el-range__icon {
        line-height: 24px;
      }
      .el-range__close-icon  {
        line-height: 24px;
        text-align: left;
      }
    }
    .el-range-separator {
      width: 10%;
      font-size: 13px;
      align-items: center;
      display: flex;
    }
  }
}
</style>
